package com.yifeixi.validation.aop;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Optional;
import javax.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author YiFeiXi
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

  private static final String SPLIT_LINE = "------------------------";

  @ExceptionHandler(BindException.class)
  @ResponseStatus(HttpStatus.OK)
  public Object bindExceptionHandler(BindException e) {
    log.error(SPLIT_LINE);
    Optional.ofNullable(e.getBindingResult().getAllErrors())
        .orElse(new ArrayList<>())
        .forEach(i -> log.error("BindException: {} {}", i.getArguments(), i.getDefaultMessage()));
    log.error(SPLIT_LINE);
    return true;
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseStatus(HttpStatus.OK)
  public Object methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
    log.error(SPLIT_LINE);
    Optional.ofNullable(e.getBindingResult().getAllErrors())
        .orElse(new ArrayList<>())
        .forEach(
            i ->
                log.error(
                    "MethodArgumentNotValidException: {} {}",
                    i.getArguments(),
                    i.getDefaultMessage()));
    log.error(SPLIT_LINE);
    return true;
  }

  @ExceptionHandler(ConstraintViolationException.class)
  @ResponseStatus(HttpStatus.OK)
  public Object exception(ConstraintViolationException e) {
    log.error(SPLIT_LINE);
    Optional.ofNullable(e.getConstraintViolations())
        .orElse(new HashSet<>())
        .forEach(
            i ->
                log.error(
                    "MethodArgumentNotValidException: {} {}",
                    i.getPropertyPath(),
                    i.getMessage()));
    log.error(SPLIT_LINE);
    return true;
  }
}
